#!/usr/bin/env bash
set -e -u

# Redirect stderr to stdout
exec 2>&1

umask "<%- config['umask'] %>"

if [ "${1}" = "start" ]; then
  echo "starting ${2}..."
  api_umbrella_user="<%- config['user'] %>"
  api_umbrella_group="<%- config['group'] %>"

  run_args=("-e" "rc.env")
  if [ -n "$api_umbrella_user" ]; then
    run_args+=("-u" "$api_umbrella_user")
  fi

  dirs=("<%- config['var_dir'] %>/trafficserver")
  mkdir -p "${dirs[@]}"
  chmod 750 "${dirs[@]}"
  if [ -n "$api_umbrella_user" ]; then
    chown "$api_umbrella_user":"$api_umbrella_group" "${dirs[@]}"
  fi

  destination="<%- config['log']['destination'] %>"
  if [ "$destination" = "console" ]; then
    if [ -n "$api_umbrella_user" ]; then
      chown "$api_umbrella_user":"$api_umbrella_group" /dev/stdout
      chown "$api_umbrella_user":"$api_umbrella_group" /dev/stderr
    fi

    ln -sf /dev/stdout "<%- config['log_dir'] %>/trafficserver/access.log"
    ln -sf /dev/stderr "<%- config['log_dir'] %>/trafficserver/diags.log"
    ln -sf /dev/stderr "<%- config['log_dir'] %>/trafficserver/manager.log"
    ln -sf /dev/stderr "<%- config['log_dir'] %>/trafficserver/traffic.out"
  fi

  exec runtool ${run_args[@]+"${run_args[@]}"} traffic_manager --nosyslog
fi

exit 0
